package device

import (
	"errors"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"sync"
	"time"
	"tools"
)

type sign struct {
	source map[string]chan int
	lock   sync.RWMutex
}

const (
	EXPIRE_IN = 5 * time.Second // 1分钟超时
)

var signc = &sign{source: map[string]chan int{}}

// 创建信号通道
func CreateSign() string {
	signc.lock.Lock()
	defer signc.lock.Unlock()

	ipaddr := beego.AppConfig.DefaultString("ipaddr", "127.0.0.1")
	httpport := beego.AppConfig.DefaultString("httpport", "9501")
	key := tools.GUUID() + "@" + ipaddr + ":" + httpport

	signc.source[key] = make(chan int)
	return key
}

// 给通道发送成功信号
func SendSign(key string) {
	if s, ok := signc.source[key]; ok {
		s <- 1
		close(s)
	} else {
		logs.Error("no signal exists")
	}
}

// 获取信号源
func GetSign(key string) (chan int, error) {
	if s, ok := signc.source[key]; ok {
		return s, nil
	}
	return nil, errors.New("no signal exists")
}

// 删除map
func DelSign(key string) {
	if _, ok := signc.source[key]; ok {
		signc.lock.Lock()
		defer signc.lock.Unlock()
		delete(signc.source, key)
	}
}
